﻿/* Copyright 2010 Igor Francé
 * 
 * This file is part of ECMADoc (http://ecmadoc.codeplex.com).
 * 
 * ECMADoc is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * ECMADoc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with ECMADoc. 
 * If not, see http://www.gnu.org/licenses/.
 */
namespace EcmaDoc.Gui
{
	using System;
	using System.Threading;

	using Core;

	/// <summary>
	/// Provides a wrapper for a separate thread that performs its work parallel to the GUI
	/// </summary>
	public class ProcessThread
	{
		private readonly Thread thread;
		private readonly ThreadStart threadStart;
		private readonly Action<Exception> exceptionHandler;

		/// <summary>
		/// Initializes a new instance of the <see cref="ProcessThread"/> class.
		/// </summary>
		/// <param name="threadStart">The delegate method to invoke with the new new thread.</param>
		/// <param name="exceptionHandler">The delegate method that handles any exceptions that occur in this thread.</param>
		public ProcessThread(ThreadStart threadStart, Action<Exception> exceptionHandler)
		{
			if (threadStart == null)
				throw new ArgumentNullException("threadStart");
			if (exceptionHandler == null)
				throw new ArgumentNullException("exceptionHandler");

			this.threadStart = threadStart;
			this.exceptionHandler = exceptionHandler;

			thread = new Thread(() =>
			{
				try
				{
					threadStart.Invoke();
				}
				catch (Exception ex)
				{
					exceptionHandler.Invoke(ex);
				}
			});
		}

		/// <summary>
		/// Starts this thread.
		/// </summary>
		public void Start()
		{
			thread.Start();
		}

		/// <summary>
		/// Aborts this thread.
		/// </summary>
		public void Abort()
		{
			Log.WriteLine(LogCategory.Debug, thread.ThreadState);
			thread.Abort();
			Log.WriteLine(LogCategory.Debug, thread.ThreadState);
		}
	}
}
